package com.icesoft.core.web.suppose.sms;

import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.web.base.BaseAnnotationInterceptor;
import com.icesoft.core.web.helper.RequestHold;
import com.icesoft.core.web.helper.ResponseUtils;
import com.icesoft.core.web.model.SmsCodeDTO;
import com.icesoft.core.web.suppose.sms.config.SmsCodeCacheService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@AllArgsConstructor
public class SmsCodeInterceptor extends BaseAnnotationInterceptor<SmsCodeCheck> {
    private SmsCodeCacheService smsCodeCacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, SmsCodeCheck annotation) {
        log.debug("短信验证码校验SmsCodeCheck");
        // 手机号校验
        String phone = RequestHold.getString(request, annotation.phone());
        log.trace("参数phone:{}", phone);
        if (phone == null) {
            ResponseUtils.writeJson(response, Resp.error("请提供手机号参数" + annotation.phone()));
            return false;
        }
        SmsCodeDTO cacheSmsCode = smsCodeCacheService.getCache(phone);
        if (cacheSmsCode == null) {
            ResponseUtils.writeJson(response, Resp.error("验证码不存在"));
            return false;
        }
        // 验证码校验
        String smsCode = RequestHold.getString(request, annotation.smsCode());
        log.trace("参数smsCode:{}", smsCode);
        if (smsCode == null) {
            ResponseUtils.writeJson(response, Resp.error("请提供验证码参数" + annotation.smsCode()));
            return false;
        }
        // 验证码校验
        if (!smsCode.equalsIgnoreCase(cacheSmsCode.getCode())) {
            ResponseUtils.writeJson(response, Resp.error("短信验证码输入有误"));
            return false;
        }
        smsCodeCacheService.remove(phone);
        return true;
    }
}
